
#include "TBPlatform.h"
#include <algorithm>
#include "Merchant.h"

TBPlatform::TBPlatform()
    : mct_vec_(std::vector<Merchant*>())
{

}

bool TBPlatform::Dispatch(const Message& msg)
{
  if (msg.get_receiver() == 0) {
    for (Merchant* m : mct_vec_)
      m->Receive(msg);
    return true;
  }
  for (Merchant* m : mct_vec_)
    if (m->git_mid() == msg.get_receiver()) {
      m->Receive(msg);
      return true;
    }
  return false;
}

void TBPlatform::Registry(Merchant* m)
{
  mct_vec_.push_back(m);
  m->set_platform(this);
}

std::vector<Commodity>* TBPlatform::Search(const std::string& key)
{
  auto* res = new std::vector<Commodity>();
  for (Merchant* m : mct_vec_)
    if (m->Sell()
         .get_key() == key)
      res->push_back(m->Sell());
  return res;
}

TBPlatform::~TBPlatform()
{
  for (Merchant* m : mct_vec_)
    delete m;
  mct_vec_.clear();
}
